package com.example.friendfindertwo;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.xml.validation.Validator;

import org.json.JSONException;
import org.json.JSONObject;

import com.example.friendfindertwo.R;
import com.example.friendfindertwo.application.StartApplication;
import model.Category;
import model.Event;
import com.google.android.gms.maps.model.LatLng;
import com.parse.ParsePush;

import android.app.ActionBar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.Spinner;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TimePicker;
import android.widget.Toast;
import android.text.Editable;
import android.text.TextWatcher;

public class CreateEventActivity extends Activity{
	private int myear;
	
	//private String location ="no location";
	private double lng;
	private double lat;
	//Declaration of the UI items
	EditText editTextTitle;
	Spinner spinnerCategorie;
	Button buttonCurrentPosition;
	EditText editTextLocation;
	EditText editTextStartDay;
	EditText editTextStartTime;
	EditText editTextEndDay;
	EditText editTextEndTime;
	EditText editTextDescription;
	EditText eLocation;
	Button buttonCreate;
	private Switch mIsPublic;
	
	Event newEvent;
	
	private Calendar mStartDate;
	private Calendar mEndDate;
	private int mStartYear;
	private int mStartMonth;
	private int mStartDay;
	private int mStartHour;
	private int mStartMinute;
	private int mEndYear;
	private int mEndMonth;
	private int mEndDay;
	private int mEndHour;
	private int mEndMinute;
	
	private int mYear;
	private int mMonth;
	private int mDay;
	private int mHour;
	private int mMinute;
	private String title;
	private String placeName;
	private final String ACCOUNT_NAME = ParseDatabase.getAccountName();
	
	private ParseDatabase mDatabase;
	
	final Calendar c = Calendar.getInstance();
    
	// Deal with event date & time
	Calendar end = (Calendar) c.clone();
    Calendar start = (Calendar) c.clone();
    
	/*
	 * SetReferences to our layout
	 */
	private void setUiReferences()
	{
		 editTextTitle=(EditText) findViewById(R.id.editTextTitle);
		 spinnerCategorie=(Spinner) findViewById(R.id.spinnerCategorie);
		 //set spinner items
		 List<String> spinnerList = StartApplication.getAllCategoryNames();
		 ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, spinnerList);
		 spinnerCategorie.setAdapter(adapter);
		 buttonCurrentPosition=(Button) findViewById(R.id.buttonCurrentPosition);
		 editTextLocation=(EditText) findViewById(R.id.editTextLocation);
		 editTextStartDay=(EditText) findViewById(R.id.editTextStartDay);
		 editTextStartTime=(EditText) findViewById(R.id.editTextStartTime);
		 editTextEndDay=(EditText) findViewById(R.id.editTextEndDay);
		 editTextEndTime=(EditText) findViewById(R.id.editTextEndTime);
		 editTextDescription=(EditText) findViewById(R.id.editTextDescription);
		 buttonCreate=(Button) findViewById(R.id.buttonCreate);
		 mIsPublic = (Switch) findViewById(R.id.create_event__privacy);
		 eLocation = (EditText) findViewById(R.id.editTextLocation);
		 
		
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_create_event);
		setUiReferences(); //To map variables with our layout

		// Getting the extra from SecondMap.java
		// If the create event button is used, we just skip this code
		if(getIntent().getExtras().getBoolean("long click"))
		{
			setLocation(getIntent().getExtras().getDouble("latitude"), getIntent().getExtras().getDouble("longitude"));						
		}else if(getIntent().getExtras().getBoolean("currentPosition")){
			setLocation(getIntent().getExtras().getDouble("current latitude"), getIntent().getExtras().getDouble("current longitude"));
		}
		try {
			placeName=getName(lat, lng);
			eLocation.setText(placeName);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("failed retreving address from latLng object");
		}
		
		// Add inputs to the global listener
		buttonCreate.setOnClickListener(mGlobal_OnClickListener);
        buttonCurrentPosition.setOnClickListener(mGlobal_OnClickListener);
        editTextStartDay.setOnClickListener(mGlobal_OnClickListener);
        editTextEndDay.setOnClickListener(mGlobal_OnClickListener);
        editTextStartTime.setOnClickListener(mGlobal_OnClickListener);
        editTextEndTime.setOnClickListener(mGlobal_OnClickListener);
        
        // get action bar   
        ActionBar actionBar = getActionBar();
        actionBar.setSubtitle(R.string.title_activity_create_event);
        
        // Enabling Up / Back navigation
        actionBar.setDisplayHomeAsUpEnabled(true);
        
        // Get current date and time
        mYear = c.get(Calendar.YEAR);
		mMonth = c.get(Calendar.MONTH);
		mDay = c.get(Calendar.DAY_OF_MONTH);
		mHour = c.get(Calendar.HOUR_OF_DAY);
        mMinute = c.get(Calendar.MINUTE);
        
        // Initialize the default event date & time parameters
        mEndYear = mStartYear = mYear;
        mEndMonth = mStartMonth = mMonth;
        mEndDay = mStartDay = mDay;
        mEndHour = mStartHour = mHour;
        mEndMinute = mStartMinute = mMinute;
		
        // Initialize edit text with default date & time
        editTextStartDay.setText(mDay + "-"+ (mMonth + 1) + "-" + mYear);
        editTextStartTime.setText(mHour + ":" + mMinute);
        
        editTextEndDay.setText(mDay + "-"+ (mMonth + 1) + "-" + mYear);
        editTextEndTime.setText(mHour + ":" + mMinute);     
        
        
	}

	//Global On click listener for all views
    final OnClickListener mGlobal_OnClickListener = new OnClickListener() {
        public void onClick(final View v) {
            switch(v.getId()) {
                case R.id.buttonCreate:
                	
                	// create parse database object
    				mDatabase = new ParseDatabase();    				    			    				    				
    				
    				// get entered data and save with parse
    				title = editTextTitle.getText().toString();

				// get entered data and save with parse
				String title = editTextTitle.getText().toString();

				//String category = spinnerCategorie.getSelectedItem().toString();
				String description = editTextDescription.getText().toString();
				LatLng location = new LatLng(lat, lng);

				Calendar end = Calendar.getInstance();
				end.set(mEndYear, mEndMonth, mEndDay, mEndHour, mEndMinute);
				Calendar start = Calendar.getInstance();
				start.set(mStartYear, mStartMonth, mStartDay, mStartHour, mStartMinute);

				// TextWatcher would let us check validation error on the fly
    		        editTextDescription.addTextChangedListener(new TextWatcher() {
    		            public void afterTextChanged(Editable s) {
    		                FormValidator.hasText(editTextDescription);
    		            }
    		            public void beforeTextChanged(CharSequence s, int start, int count, int after){}
    		            public void onTextChanged(CharSequence s, int start, int before, int count){}
    		        });
    		        
    		        editTextTitle.addTextChangedListener(new TextWatcher() {
    		            public void afterTextChanged(Editable s) {
    		                FormValidator.hasText(editTextTitle);
    		            }
    		            public void beforeTextChanged(CharSequence s, int start, int count, int after){}
    		            public void onTextChanged(CharSequence s, int start, int before, int count){}
    		        });
    		        
    		        
    		        if(checkValidation()){
    		        	end.set(mEndYear, mEndMonth, mEndDay, mEndHour, mEndMinute);		
    		    		start.set(mStartYear, mStartMonth, mStartDay, mStartHour, mStartMinute);
    		    		newEvent = new Event(title, description, spinnerCategorie.getSelectedItem().toString(), location, start.getTime(), end.getTime(), placeName,StartApplication.getCurrentUser(), mIsPublic.isChecked());
    					String objectId= mDatabase.saveEventOnDataBase(newEvent);
    					newEvent.setObjectId(objectId);
    					//StartApplication.addEvent(newEvent);
    					try {
    						sendPushNotification();
    					} catch (JSONException e) {
    						// TODO Auto-generated catch block
    						e.printStackTrace();
    					}
        				//mDatabase.saveEventOnDataBase(location, start.getTime(), end.getTime(), description, title, mIsPublic.isChecked());
    					//    				newEvent= new Event("test event", "test description", 
    					//					"MockCategorie", "MackPlace", new LatLng(0, 0), new Date(), 
    					//					 new Date(), new Date(), friend);
    		        	finish();    		        	
    		        }	
    		        
                break;

                case R.id.editTextLocation:
                	String string = editTextLocation.getText().toString();                	
                	if(string.contains(" ")){
	                	lat= Double.parseDouble(string.substring(0, string.indexOf(" "))); 
	                	lng= Double.parseDouble(string.substring(1, string.indexOf(" ")));
                	}
                	
                	setLocation(lat, lng);
                	break;
                case R.id.editTextStartDay:                	                	                	                                
                	setDatePicker(editTextStartDay);                
                	break;
                case R.id.editTextEndDay:
                	setDatePicker(editTextEndDay);
                	break;
                case R.id.editTextStartTime:
                	setTimePicker(editTextStartTime);
                	break;
                case R.id.editTextEndTime:
                	setTimePicker(editTextEndTime);
                }
        }
    };



    
    public void setDatePicker(final EditText field){    			
		// Launch Date Picker Dialog
		 DatePickerDialog dpd = new DatePickerDialog(CreateEventActivity.this,
                    new DatePickerDialog.OnDateSetListener() {
 
                        @Override
                        public void onDateSet(DatePicker view, int year,
                                int monthOfYear, int dayOfMonth) {
                            // Display Selected date in textbox
                        	field.setText(dayOfMonth + "-"
                                    + (monthOfYear + 1) + "-" + year);
 
                        	switch (field.getId()){
                        	case R.id.editTextStartDay:
                        		mStartYear = year;
                        		mStartMonth = monthOfYear;
                        		mStartDay = dayOfMonth;
                        	case R.id.editTextEndDay:
                        		mEndYear = year;
                        		mEndMonth = monthOfYear;
                        		mEndDay = dayOfMonth;
                        	}

                        }
                    }, mYear, mMonth, mDay);
            dpd.show();

    }
    
    public void setTimePicker(final EditText field){    	        
        // Launch Time Picker Dialog
        TimePickerDialog tpd = new TimePickerDialog(this,
                new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay,
                            int minute) {
                        // Display Selected time in textbox
                        field.setText(hourOfDay + ":" + minute);
                        switch (field.getId()){
                        case R.id.editTextEndTime:
                        	mEndHour = hourOfDay;
                        	mEndMinute = minute;
                        case R.id.editTextStartTime:
                        	mStartHour = hourOfDay;
                        	mStartMinute = minute;
                        }
                    }
                }, mHour, mMinute, false);
        tpd.show();

    }
    
	private void sendPushNotification() throws JSONException {
		ParsePush push = new ParsePush();
		push.setChannel("userTable");
		JSONObject data = new JSONObject();
		data.put("action", "com.example.friendfindertwo.UPDATE_EVENT");
		data.put("account_name", ACCOUNT_NAME);
		data.put("event_title", title);
		data.put("title", title);
//		JSONObject data = new JSONObject("{\"action\": \"com.example.friendfindertwo.UPDATE_EVENT\","\"account_name\": \""+ACCOUNT_NAME+"\","\"title\": \""+title+"\"}\"");
		push.setData(data);
		push.sendInBackground();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.create_event, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	 private boolean checkValidation() {
	        boolean ret = true;
	 
	        if (!FormValidator.hasText(editTextDescription)) ret = false;
	        if (!FormValidator.hasText(editTextTitle)) ret = false;	        	 
	        return ret;
	}
	 
	private void setLocation(double lat, double lng) {
		this.lat = lat;
		this.lng = lng;
	}
	
	 private String getName(double latitude,double longitude) throws IOException
	 { 
		  String add="";
		  double p1 = latitude;
		  double p2 = longitude;
		  Geocoder geocoder = new Geocoder(this, Locale.getDefault());
		  try
		  {
               List addresses = geocoder.getFromLocation(p1, p2, 1);
               Address obj = (Address) addresses.get(0);
               add = obj.getAddressLine(0) +" "+obj.getAddressLine(1)+" "                                                          + obj.getAddressLine(2);
		  }
		  catch(Exception ex)
		  {
			  Toast.makeText(this,"exception"+ex.getMessage(),Toast.LENGTH_LONG).show();            
		  }
		  return add;
	 }
}
